package com.tfb.boot;

public class test {
    public static void main(String[] args) {
        Dianyuan dianyuan = new Dianyuan();
        Xiaofei xiaofei = new Xiaofei(dianyuan);
        Shengchan shengchan = new Shengchan(dianyuan);
        shengchan.start();
        xiaofei.start();
    }
}
class Dianyuan{
    int baozi=0;

    public synchronized void shengchan(){


        if (baozi<20){
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            baozi++;
            System.out.println("这是生产的第"+baozi+"个包子");
            notify();
        }else {
            try {
                System.out.println("生产开始等待");
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
    public synchronized void xiaofei(){


        if (baozi>0){
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            baozi--;
            System.out.println("这是消费的第"+baozi+"个包子");
            notify();
        }else {
            try {
                System.out.println("消费开始等待");
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

class Shengchan extends Thread{
    private Dianyuan dianyuan;
    Shengchan(Dianyuan dianyuan){
        this.dianyuan=dianyuan;
    }
    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("开始生产");
        while (true){
            dianyuan.shengchan();
        }
    }
}

class Xiaofei extends Thread{
    private Dianyuan dianyuan;
    Xiaofei(Dianyuan dianyuan){
        this.dianyuan=dianyuan;
    }
    @Override
    public void run() {
        System.out.println("开始消费");
        while (true){
            dianyuan.xiaofei();
        }
    }
}
